<template>
  <div class="chart-container">
    <el-card>
      <div class="filter-bar">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="fetchChartData"
        />
      </div>
      <div ref="chartRef" class="echart" style="height: 400px; width: 100%"></div>
    </el-card>
    <el-card style="margin-top: 24px">
      <div style="font-weight: bold; font-size: 16px; margin-bottom: 8px">充值数据统计</div>
      <div ref="rechargeChartRef" class="echart" style="height: 320px; width: 100%"></div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echartsCore from 'echarts/core';
import { LineChart, BarChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { ElMessage } from 'element-plus';
import { getPaymentChartData } from '@/api/payment';
import dayjs from 'dayjs';

echartsCore.use([LineChart, BarChart, TitleComponent, TooltipComponent, GridComponent, LegendComponent, CanvasRenderer]);

const chartRef = ref<HTMLDivElement | null>(null);
const chartInstance = ref<any>(null);
const dateRange = ref<any[]>([]);
const chartData = ref({
  dates: [] as string[],
  amounts: [] as number[],
  counts: [] as number[],
  rechargeAmounts: [] as number[],
  rechargeCounts: [] as number[]
});

const rechargeChartRef = ref<HTMLDivElement | null>(null);
let rechargeChartInstance: any = null;

const resizeHandler = () => {
  chartInstance.value?.resize();
};

const processData = (data: any[]) => {
  const dateMap = new Map<string, { amount: number; count: number; rechargeAmount: number; rechargeCount: number }>();
  data.forEach((item) => {
    const date = dayjs(item.createTime).format('YYYY-MM-DD');
    if (!dateMap.has(date)) {
      dateMap.set(date, { amount: 0, count: 0, rechargeAmount: 0, rechargeCount: 0 });
    }
    const stat = dateMap.get(date)!;
    if (!item.orderId) {
      stat.rechargeAmount += Number(item.paymentAmount) || 0;
      stat.rechargeCount += 1;
    } else {
      stat.amount += Number(item.paymentAmount) || 0;
      stat.count += 1;
    }
  });
  const sortedDates = Array.from(dateMap.keys()).sort();
  chartData.value = {
    dates: sortedDates,
    amounts: sortedDates.map((date) => {
      const v = dateMap.get(date)?.amount;
      return typeof v === 'number' && !isNaN(v) ? v : 0;
    }),
    counts: sortedDates.map((date) => {
      const v = dateMap.get(date)?.count;
      return typeof v === 'number' && !isNaN(v) ? v : 0;
    }),
    rechargeAmounts: sortedDates.map((date) => {
      const v = dateMap.get(date)?.rechargeAmount;
      return typeof v === 'number' && !isNaN(v) ? v : 0;
    }),
    rechargeCounts: sortedDates.map((date) => {
      const v = dateMap.get(date)?.rechargeCount;
      return typeof v === 'number' && !isNaN(v) ? v : 0;
    })
  };
};

const initChart = () => {
  if (!chartRef.value) return;
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }
  chartInstance.value = echartsCore.init(chartRef.value);
  window.addEventListener('resize', resizeHandler);

  const { dates, amounts, counts, rechargeAmounts, rechargeCounts } = chartData.value;
  const safeArray = (arr: any[], len: number) => {
    if (!Array.isArray(arr)) return Array(len).fill(0);
    const result = [];
    for (let i = 0; i < len; i++) {
      const v = arr[i];
      result.push(typeof v === 'number' && !isNaN(v) ? v : 0);
    }
    return result;
  };
  //   console.log(dates, amounts, counts)
  const safeDates = Array.isArray(dates) ? dates.map((d) => (typeof d === 'string' ? d : '')) : [];
  const safeAmounts = safeArray(amounts, safeDates.length);
  const safeCounts = safeArray(counts, safeDates.length);
  const safeRechargeAmounts = safeArray(rechargeAmounts, safeDates.length);
  const safeRechargeCounts = safeArray(rechargeCounts, safeDates.length);
  const hasData =
    safeDates.length > 0 &&
    safeAmounts.length === safeDates.length &&
    safeCounts.length === safeDates.length &&
    safeRechargeAmounts.length === safeDates.length &&
    safeRechargeCounts.length === safeDates.length;
  console.log(safeAmounts);
  const option = hasData
    ? {
        title: {
          text: '支付数据统计',
          left: 'center',
          top: 10,
          textStyle: { fontSize: 22, fontWeight: 'bold', color: '#409EFF', fontFamily: 'PingFang SC, Microsoft YaHei, Arial' }
        },
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(255,255,255,0.98)',
          borderColor: '#90caf9',
          borderWidth: 1,
          textStyle: { color: '#409EFF', fontSize: 15, fontWeight: 'bold' },
          axisPointer: { type: 'shadow' },
          extraCssText: 'box-shadow: 0 4px 16px rgba(64,158,255,0.12); border-radius: 10px;',
          formatter: function (params) {
            if (!params) return '';
            let result = `<div style='font-weight:bold;margin-bottom:2px;color:#409EFF;'>${params.name}</div>`;
            if (params.seriesName === '支付金额') {
              result += `<span style='display:inline-block;margin-right:8px;'>${params.marker}</span><span style='color:#409EFF;'>支付金额</span>: <b>${params.value}</b> 元`;
            } else if (params.seriesName === '支付笔数') {
              result += `<span style='display:inline-block;margin-right:8px;'>${params.marker}</span><span style='color:#67C23A;'>支付笔数</span>: <b>${params.value}</b> 笔`;
            }
            return result;
          }
        },
        legend: {
          data: ['支付金额', '支付笔数'],
          top: 20,
          right: 120,
          icon: 'roundRect',
          itemWidth: 22,
          itemHeight: 14,
          textStyle: { fontSize: 16, color: '#409EFF', fontWeight: 'bold' },
          selectedMode: false
        },
        grid: {
          left: '4%',
          right: '4%',
          bottom: '8%',
          containLabel: true,
          backgroundColor: '#E3F2FD',
          borderRadius: 12
        },
        xAxis: {
          type: 'category',
          boundaryGap: true,
          data: safeDates,
          axisLabel: {
            rotate: 30,
            color: '#409EFF',
            fontSize: 15,
            fontWeight: 'bold',
            margin: 16
          },
          axisLine: { lineStyle: { color: '#90caf9', width: 2 } },
          axisTick: { show: false }
        },
        yAxis: [
          {
            type: 'value',
            name: '金额(元)',
            position: 'left',
            axisLabel: { formatter: '{value}', color: '#409EFF', fontSize: 15, fontWeight: 'bold' },
            splitLine: { show: true, lineStyle: { color: '#BBDEFB', type: 'dashed' } },
            nameTextStyle: { color: '#409EFF', fontSize: 15, fontWeight: 'bold' },
            axisLine: { lineStyle: { color: '#409EFF' } },
            axisTick: { show: true },
            splitNumber: 4
          },
          {
            type: 'value',
            name: '笔数',
            position: 'right',
            axisLabel: { formatter: '{value}', color: '#67C23A', fontSize: 15, fontWeight: 'bold' },
            splitLine: { show: false },
            nameTextStyle: { color: '#67C23A', fontSize: 15, fontWeight: 'bold' }
          }
        ],
        series: [
          {
            name: '支付金额',
            type: 'bar',
            data: safeAmounts,
            yAxisIndex: 0,
            barWidth: 20,
            barGap: '30%',
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: '#409EFF' },
                  { offset: 1, color: '#b3d8ff' }
                ]
              },
              borderRadius: [12, 12, 0, 0],
              shadowColor: 'rgba(64,158,255,0.22)',
              shadowBlur: 16
            },
            emphasis: {
              itemStyle: { color: '#1d8fff' }
            }
          },
          {
            name: '支付笔数',
            type: 'line',
            yAxisIndex: 1,
            data: safeCounts,
            smooth: true,
            showSymbol: true,
            symbol: 'circle',
            symbolSize: 18,
            itemStyle: { color: '#67C23A', borderColor: '#fff', borderWidth: 4, shadowColor: '#67C23A', shadowBlur: 10 },
            lineStyle: { width: 6, color: '#67C23A', shadowColor: '#67C23A', shadowBlur: 10 },
            emphasis: { focus: 'series', itemStyle: { borderColor: '#67C23A', borderWidth: 6 } }
          }
        ]
      }
    : {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'center',
          textStyle: { fontSize: 18, color: '#bbb' }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '暂无数据',
          backgroundColor: '#fff',
          borderColor: '#eee',
          borderWidth: 1,
          textStyle: { color: '#333', fontSize: 14 }
        },
        xAxis: { type: 'category', data: [] },
        yAxis: [{ type: 'value' }, { type: 'value' }],
        series: []
      };

  chartInstance.value.setOption(option, true);
};

const initRechargeChart = () => {
  if (!rechargeChartRef.value) return;
  if (rechargeChartInstance) {
    rechargeChartInstance.dispose();
  }
  rechargeChartInstance = echartsCore.init(rechargeChartRef.value);
  const { dates, rechargeAmounts, rechargeCounts } = chartData.value;
  const safeArray = (arr: any[], len: number) => {
    if (!Array.isArray(arr)) return Array(len).fill(0);
    const result = [];
    for (let i = 0; i < len; i++) {
      const v = arr[i];
      result.push(typeof v === 'number' && !isNaN(v) ? v : 0);
    }
    return result;
  };
  const safeDates = Array.isArray(dates) ? dates.map((d) => (typeof d === 'string' ? d : '')) : [];
  const safeRechargeAmounts = safeArray(rechargeAmounts, safeDates.length);
  const safeRechargeCounts = safeArray(rechargeCounts, safeDates.length);
  const hasData = safeDates.length > 0 && safeRechargeAmounts.length === safeDates.length && safeRechargeCounts.length === safeDates.length;
  console.log(safeRechargeAmounts);
  const maxRecharge = Math.max(...safeRechargeAmounts, 10); // 至少10
  const rechargeYAxisMax = maxRecharge > 0 ? Math.ceil(maxRecharge * 1.2) : 10;
  const option = hasData
    ? {
        title: {
          text: '充值数据统计',
          left: 'center',
          top: 10,
          textStyle: { fontSize: 22, fontWeight: 'bold', color: '#FF9800', fontFamily: 'PingFang SC, Microsoft YaHei, Arial' }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255,255,255,0.98)',
          borderColor: '#FFD180',
          borderWidth: 1,
          textStyle: { color: '#FF9800', fontSize: 15, fontWeight: 'bold' },
          axisPointer: { type: 'shadow' },
          extraCssText: 'box-shadow: 0 4px 16px rgba(255,152,0,0.12); border-radius: 10px;',
          formatter: function (params) {
            if (!params || !params.length) return '';
            let result = `<div style='font-weight:bold;margin-bottom:2px;color:#FF9800;'>${params[0].name}</div>`;
            params.forEach((item) => {
              if (item.seriesName === '充值金额') {
                result += `<span style='display:inline-block;margin-right:8px;'>${item.marker}</span><span style='color:#FF9800;'>充值金额</span>: <b>${item.value}</b> 元<br/>`;
              } else if (item.seriesName === '充值笔数') {
                result += `<span style='display:inline-block;margin-right:8px;'>${item.marker}</span><span style='color:#FF7043;'>充值笔数</span>: <b>${item.value}</b> 笔<br/>`;
              }
            });
            return result;
          }
        },
        legend: {
          data: ['充值金额', '充值笔数'],
          top: 20,
          right: 120,
          icon: 'roundRect',
          itemWidth: 22,
          itemHeight: 14,
          textStyle: { fontSize: 16, color: '#FF9800', fontWeight: 'bold' },
          selectedMode: false
        },
        grid: {
          left: '4%',
          right: '4%',
          bottom: '8%',
          containLabel: true,
          backgroundColor: '#FFF8E1',
          borderRadius: 12
        },
        xAxis: {
          type: 'category',
          boundaryGap: true,
          data: safeDates,
          axisLabel: {
            rotate: 30,
            color: '#FF9800',
            fontSize: 15,
            fontWeight: 'bold',
            margin: 16
          },
          axisLine: { lineStyle: { color: '#FFB300', width: 2 } },
          axisTick: { show: false }
        },
        yAxis: [
          {
            type: 'value',
            name: '金额(元)',
            position: 'left',
            min: 0,
            max: 10000,
            interval: 500,
            axisLabel: {
              formatter: function (value) {
                if (value === 0) return '0';
                if (value === 500) return '500';
                if (value === 1000) return '1000';
                if (value === 5000) return '5000';
                if (value === 10000) return '10000';
                return '';
              },
              color: '#FF9800',
              fontSize: 15,
              fontWeight: 'bold'
            },
            splitLine: { show: true, lineStyle: { color: '#FFE0B2', type: 'dashed' } },
            nameTextStyle: { color: '#FF9800', fontSize: 15, fontWeight: 'bold' },
            axisLine: { lineStyle: { color: '#FF9800' } },
            axisTick: { show: true },
            splitNumber: 4
          },
          {
            type: 'value',
            name: '笔数',
            position: 'right',
            axisLabel: { formatter: '{value}', color: '#FF7043', fontSize: 15, fontWeight: 'bold' },
            splitLine: { show: false },
            nameTextStyle: { color: '#FF7043', fontSize: 15, fontWeight: 'bold' }
          }
        ],
        series: [
          {
            name: '充值金额',
            type: 'bar',
            data: safeRechargeAmounts,
            yAxisIndex: 0,
            barWidth: 20,
            barGap: '30%',
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: '#FFB300' },
                  { offset: 1, color: '#FFE082' }
                ]
              },
              borderRadius: [12, 12, 0, 0],
              shadowColor: 'rgba(255,179,0,0.22)',
              shadowBlur: 16
            },
            emphasis: {
              itemStyle: { color: '#FFA000' }
            }
          },
          {
            name: '充值笔数',
            type: 'line',
            yAxisIndex: 1,
            data: safeRechargeCounts,
            smooth: true,
            showSymbol: true,
            symbol: 'circle',
            symbolSize: 18,
            itemStyle: { color: '#FF7043', borderColor: '#fff', borderWidth: 4, shadowColor: '#FF7043', shadowBlur: 10 },
            lineStyle: { width: 6, color: '#FF7043', shadowColor: '#FF7043', shadowBlur: 10 },
            emphasis: { focus: 'series', itemStyle: { borderColor: '#FF7043', borderWidth: 6 } }
          }
        ]
      }
    : {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'center',
          textStyle: { fontSize: 18, color: '#bbb' }
        },
        xAxis: { type: 'category', data: [] },
        yAxis: [{ type: 'value' }, { type: 'value' }],
        series: []
      };
  rechargeChartInstance.setOption(option, true);
};

const fetchChartData = async () => {
  try {
    const params: any = {};
    let begin = null,
      end = null;
    if (dateRange.value && dateRange.value.length === 2) {
      begin = dayjs(dateRange.value[0]).startOf('day');
      end = dayjs(dateRange.value[1]).endOf('day');
    }
    const res = await getPaymentChartData(params);
    let filteredData = res.data || [];
    if (begin && end) {
      filteredData = filteredData.filter((item) => {
        const t = dayjs(item.createTime);
        return (t.isAfter(begin) || t.isSame(begin, 'day')) && (t.isBefore(end) || t.isSame(end, 'day'));
      });
    }
    if (filteredData.length) {
      processData(filteredData);
      initChart();
      initRechargeChart();
    } else {
      ElMessage.warning('没有获取到数据');
      chartData.value = { dates: [], amounts: [], counts: [], rechargeAmounts: [], rechargeCounts: [] };
      initChart();
      initRechargeChart();
    }
  } catch (e) {
    console.error(e);
    ElMessage.error('获取数据失败');
    chartData.value = { dates: [], amounts: [], counts: [], rechargeAmounts: [], rechargeCounts: [] };
    initChart();
    initRechargeChart();
  }
};

onMounted(() => {
  const endDate = dayjs();
  const startDate = endDate.subtract(7, 'day');
  dateRange.value = [startDate.toDate(), endDate.toDate()];
  fetchChartData();
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeHandler);
  chartInstance.value?.dispose();
  if (rechargeChartInstance) {
    rechargeChartInstance.dispose();
    rechargeChartInstance = null;
  }
});

function tooltipFormatter(params) {
  if (!params) return '';
  if (Array.isArray(params)) {
    let result = `<div style='font-weight:bold;margin-bottom:2px;'>${params[0].name}</div>`;
    params.forEach((item) => {
      if (item.seriesName === '支付金额') {
        result += `<span style='display:inline-block;margin-right:8px;'>${item.marker}</span><span style='color:#409EFF;'>支付金额</span>: <b>${item.value}</b> 元<br/>`;
      } else if (item.seriesName === '充值金额') {
        result += `<span style='display:inline-block;margin-right:8px;'>${item.marker}</span><span style='color:#F7BA2A;'>充值金额</span>: <b>${item.value}</b> 元<br/>`;
      } else if (item.seriesName === '支付笔数') {
        result += `<span style='display:inline-block;margin-right:8px;'>${item.marker}</span><span style='color:#67C23A;'>支付笔数</span>: <b>${item.value}</b> 笔<br/>`;
      } else if (item.seriesName === '充值笔数') {
        result += `<span style='display:inline-block;margin-right:8px;'>${item.marker}</span><span style='color:#F7BA2A;'>充值笔数</span>: <b>${item.value}</b> 笔<br/>`;
      }
    });
    return result;
  } else {
    // item trigger
    let result = `<div style='font-weight:bold;margin-bottom:2px;'>${params.name}</div>`;
    if (params.seriesName === '支付金额') {
      result += `<span style='display:inline-block;margin-right:8px;'>${params.marker}</span><span style='color:#409EFF;'>支付金额</span>: <b>${params.value}</b> 元`;
    } else if (params.seriesName === '充值金额') {
      result += `<span style='display:inline-block;margin-right:8px;'>${params.marker}</span><span style='color:#F7BA2A;'>充值金额</span>: <b>${params.value}</b> 元`;
    } else if (params.seriesName === '支付笔数') {
      result += `<span style='display:inline-block;margin-right:8px;'>${params.marker}</span><span style='color:#67C23A;'>支付笔数</span>: <b>${params.value}</b> 笔`;
    } else if (params.seriesName === '充值笔数') {
      result += `<span style='display:inline-block;margin-right:8px;'>${params.marker}</span><span style='color:#F7BA2A;'>充值笔数</span>: <b>${params.value}</b> 笔`;
    }
    return result;
  }
}
</script>

<style scoped>
.chart-container {
  padding: 24px;
}

.echart {
  width: 100%;
  min-height: 400px;
  height: 400px;
}

.filter-bar {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
}
</style>
